<template>
  <el-card v-loading="companyLoading">
    <div class="dashboard-container">
      <!-- 左侧地图区域 -->
      <div class="map-container">
        <div class="header">
          <span>用能图表</span>
        </div>
        <div class="map-content">
          <DailyWaterUsageChart />
          <DailyElectricityUsageChart v-if="electricityVisible" @hasData="handleDataVisible" />
        </div>
      </div>
      <el-divider class="responsive-divider" direction="vertical" />
      <!-- 右侧信息面板 -->
      <div class="right-panel">
        <div class="alarm-section">
          <div class="header">
            <span>异常处理</span>
            <el-button size="small" type="primary" @click="navigateToAlarm">查看更多</el-button>
          </div>
          <div v-loading="alarmLoading" element-loading-text="正在收集异常信息..." class="alarm-content">
            <div class="alarm-statistics">
              <!-- 状态计数器 -->
              <div class="status-cards">
                <div class="alert-card">
                  <div class="alert-icon">
                    <i class="fa fa-exclamation-triangle icon"></i>
                  </div>
                  <div class="count-info">
                    <AnimatedNumber :decimals="0" color="#e85656"
                      :value="alarms.filter(alarm => dayjs(alarm.time).isSame(dayjs(), 'day')).length" suffix="条"
                      :duration="1000" />
                    <div class="label">今日报警</div>
                  </div>
                </div>
                <div class="pending-card">
                  <div class="alert-icon">
                    <i class="fa fa-clock-o icon"></i>
                  </div>
                  <div class="count-info">
                    <AnimatedNumber :decimals="0" color="#F5A623" :value="unresolvedAlarmsTotal" suffix="条"
                      :duration="1000" />
                    <div class="label">待处理报警</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="alarm-list-container">
              <div style="height: 100%;overflow: auto;padding: 0 12px;">
                <template v-if="unresolvedAlarms.length > 0">
                  <AlertList type="simple" :alarms="unresolvedAlarms" @refreshData="getAlarmData" />
                </template>
                <div v-else class="empty-state">
                  <i class="el-icon-chat-dot-square empty-icon"></i>
                  <p class="empty-text">暂无告警信息</p>
                  <p class="empty-desc">当前系统运行正常，没有需要处理的告警</p>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-divider />
        <div class="status-section">
          <div class="header">
            <span>设备状态</span>
            <el-button type="primary" size="small" @click="getDeviceStatusData">刷新</el-button>
          </div>
          <el-card class="status-chart-container clickable-chart" shadow="hover" body-style="padding: 0; height: 100%;"
            @click="navigateToDeviceStatus">
            <div class="chart-wrapper">
              <BasePieChart :showLabel="true" :custom-colors="['#67C23A', '#999', '#f5a623']" :data="deviceStatus"
                :isDonut="true" :showValue="true" width="100%" height="100%">
              </BasePieChart>

              <!-- 悬浮提示层 - 现在在右下角 -->
              <div class="chart-tooltip-overlay">
                <div class="chart-tooltip">
                  <i class="el-icon-view"></i>
                  <span>查看异常设备</span>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { handleError } from "@/utils/handleError";
import AnimatedNumber from "@/components/animate/AnimatedNumber.vue";
import BasePieChart from "@/components/chart/BasePieChart.vue";
import AlertList from "@/views/WarningCenter/ExceptionHandling/components/AlertList.vue";
import { useCompanyStore } from "@/stores/company";
import { useAlarmStore } from "@/stores/alarm";
import { getEventApi, getDeviceStatus } from "@/api/event";
import { events } from '@/constants'
import { getTypeLabel } from '@/utils/device';
import dayjs from "dayjs";
import { useAreaStore } from "@/stores/area";

const router = useRouter();
const areaStore = useAreaStore();
const alarmStore = useAlarmStore();
const alarmLoading = ref(false);

function navigateToAlarm() {
  router.push({
    name: 'ExceptionHandling'
  });
}

const electricityVisible = ref(true);
function handleDataVisible(hasData) {
  electricityVisible.value = hasData;
}

// 实时告警数据
const alarms = ref([]);
const meterList = ref([]);
const unresolvedAlarms = computed(() => {
  return alarms.value
    .filter(alarm => alarm.status === 1)
    .slice(0, 3);  // 列表只显示前3条
});

// 新增总数量计算属性
const unresolvedAlarmsTotal = computed(() => {
  return alarms.value.filter(alarm => alarm.status === 1).length;
});

// 跳转到离线及异常设备页面
const navigateToDeviceStatus = () => {
  // 只有当有离线或异常设备时才跳转
  if (deviceStatus.value[1].value > 0 || deviceStatus.value[2].value > 0) {
    router.push({
      name: 'OfflineErrorDevices'
    });
  }
};

function getTitle(item) {
  if (!item) return '';
  const { src_id, event_id, time, value } = item;
  if (!src_id || !event_id) return '';
  const eventConfig = events.find(event => event.id === event_id);
  if (!eventConfig || !eventConfig.format) return '';

  const params = {
    area: item.area,
    meter_code: item.meter_code,
    type: item.type ? getTypeLabel(item.type) : '',
    time: item.time ? dayjs(item.time).format('YYYY-MM-DD HH:mm:ss') : '',
    value: item.value ?? ''
  };

  try {
    return eventConfig.format(params);
  } catch (error) {
    console.error('Format error:', error);
    return '';
  }
}

function processAlarmData(data) {
  if (!Array.isArray(data)) return [];
  const processedAlarms = data.map((item) => {
    if (!item) return null;
    const meterInfo = meterList.value.find(meter => meter.id === item.src_id);
    const event = events.find(event => event.id === item.event_id);
    return {
      ...item,
      title: getTitle(item),
      time: dayjs(item.time).format('YYYY-MM-DD HH:mm:ss'),
      severityText: item.agent_level === 1 ? '严重' : item.severity === 2 ? '警告' : '提示',
      type: event?.category || '未知类型',
      update_time: item.updated_at ? dayjs(item.updated_at).fromNow() : '',
      location: meterInfo?.installation_location || '未知位置',
      area: areaStore.getAreaNameById(meterInfo?.area_id) || '未知区域',
      status: item.status || 1
    };
  }).filter(Boolean);

  // 更新 alarmStore 中的未处理告警数量
  const unresolvedCount = processedAlarms.filter(alarm => alarm.status === 1).length;
  alarmStore.setUnresolvedCount(unresolvedCount);

  return processedAlarms;
}

async function getAlarmData() {
  try {
    const res = await getEventApi({
      id: useCompanyStore().currentCompany.id,
    });
    alarms.value = processAlarmData(res.data);
  } catch (error) {
    handleError(error);
  }
}

// 设备状态数据
const deviceStatus = ref([
  { name: "在线设备", value: 0 },
  { name: "离线设备", value: 0 },
  { name: "异常设备", value: 0 },
]);

let deviceStatusLoading = ref(false);
const companyLoading = ref(false);

watch(() => useCompanyStore().currentCompany, async () => {
  companyLoading.value = true;
  try {
    await getDeviceStatusData();
    await getAlarmData();
    electricityVisible.value = true;
  } finally {
    companyLoading.value = false;
  }
}, {
  deep: true,
  immediate: true,
});

async function getDeviceStatusData() {
  deviceStatusLoading.value = true;
  deviceStatus.value = [
    { name: "在线设备", value: 0 },
    { name: "离线设备", value: 0 },
    { name: "异常设备", value: 0 },
  ];
  try {
    let res = await getDeviceStatus({
      id: useCompanyStore().currentCompany.id,
    });
    res.data.status.forEach((item) => {
      if (item.status === 1) {
        deviceStatus.value[1].value += 1;
      } else if (item.status === 2) {
        deviceStatus.value[0].value += 1;
      } else if (item.status === 3) {
        deviceStatus.value[2].value += 1;
      }
    });
  } catch (error) {
    handleError(error, "获取设备状态失败");
  } finally {
    deviceStatusLoading.value = false;
  }
}
</script>

<style scoped>
.dashboard-container {
  height: 600px;
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.map-container {
  height: 100%;
  display: flex;
  flex: 1;
  flex-direction: column;
  min-width: 500px;
}

.header {
  margin-bottom: 12px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-primary);
  height: 32px;
}

.map-content {
  flex: 1;
  border-radius: 12px;
  height: calc(100% - 44px);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.right-panel {
  height: 100%;
  margin-left: 16px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.alarm-section {
  display: flex;
  width: 100%;
  flex-direction: column;
  align-items: flex-start;
  height: 50%;
}

.alarm-content {
  display: flex;
  width: 100%;
  height: calc(100% - 44px);
}

.alarm-statistics {
  width: 28%;
  margin-right: 16px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.alarm-list-container {
  flex: 1;
  width: 400px;
  overflow: auto;
  height: 100%;
  padding: 12px 0;
  border-radius: 12px;
  border: 1px solid var(--el-border-color);
}

.status-section {
  flex: 1;
  height: 44%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.status-chart-container {
  flex: 1;
  width: 100%;
  height: calc(100% - 44px);
  position: relative;
}

.chart-wrapper {
  position: relative;
  height: 100%;
  width: 100%;
}

/* 设备状态图表的点击效果 */
.clickable-chart {
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.clickable-chart:hover {
  box-shadow: var(--el-box-shadow-light);
  border-color: var(--el-border-color-lighter);
}

/* 悬浮提示层 */
.chart-tooltip-overlay {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
  opacity: 0;
  transition: opacity 0.3s;
}

.clickable-chart:hover .chart-tooltip-overlay {
  opacity: 1;
}

.chart-tooltip {
  background-color: var(--el-color-white);
  padding: 4px 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
  border: 1px solid var(--el-border-color-lighter);
}

.chart-tooltip i {
  color: var(--el-color-primary);
  font-size: 14px;
}

.chart-tooltip span {
  color: var(--el-color-text-secondary);
  font-size: 12px;
}

.status-cards {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.alert-card,
.pending-card {
  flex: 1;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 12px;
}

.alert-card {
  background-color: #f8d8d8;
  border: 1px solid #e85656;
}

.pending-card {
  background-color: #f9e9d8;
  margin-bottom: 0;
  border: 1px solid #ef9c44;
}

.alert-card .icon {
  font-size: 40px;
  color: #e85656;
}

.pending-card .icon {
  font-size: 40px;
  color: #f5a623;
}

.alert-card .label,
.pending-card .label {
  font-size: 14px;
  color: #000;
}

.count-info {
  text-align: center;
  margin-bottom: 8px;
}

.responsive-divider {
  display: none;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-width: 300px;
  color: var(--el-text-color-secondary);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: var(--el-text-color-placeholder);
}

.empty-text {
  font-size: 16px;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
}

.empty-desc {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

/* 平板端适配 */
@media screen and (max-width: 1400px) {
  .dashboard-container {
    flex-direction: column;
    height: auto;
  }

  .map-container {
    width: 100%;
    margin-bottom: 16px;
    min-width: auto;
  }

  .map-content {
    height: calc(100% - 32px);
    min-height: 350px;
  }

  .responsive-divider {
    display: none;
  }

  .right-panel {
    margin-left: 0;
  }

  .alarm-content {
    flex-direction: row;
    height: 260px;
  }

  .alarm-statistics {
    width: 40%;
  }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .dashboard-container {
    height: auto;
    padding: 0;
  }

  .map-container {
    height: 500px;
    /* 增加移动端容器高度 */
    min-width: auto;
  }

  .map-content {
    height: calc(100% - 32px);
    min-height: 300px;
    /* 增加移动端最小高度 */
  }

  .alarm-content {
    flex-direction: column;
    height: auto;
  }

  .alarm-statistics {
    width: 100%;
    margin-right: 0;
    margin-bottom: 16px;
  }

  .status-cards {
    flex-direction: row;
    gap: 12px;
    height: auto;
  }

  .alert-card,
  .pending-card {
    margin: 0;
    height: 120px;
  }

  .alarm-section {
    height: auto;
    margin-bottom: 16px;
  }

  .status-section {
    height: 300px;
    margin-top: 16px;
  }

  .status-chart-container {
    height: calc(100% - 32px);
    min-height: 250px;
  }

  .header {
    margin-bottom: 8px;
    height: 24px;
  }

  .alert-card .icon,
  .pending-card .icon {
    font-size: 32px;
  }

  .count-info {
    margin-bottom: 4px;
  }

  .right-panel {
    height: auto;
  }

  .empty-icon {
    font-size: 36px;
    margin-bottom: 12px;
  }

  .empty-text {
    font-size: 14px;
    margin-bottom: 6px;
  }

  .empty-desc {
    font-size: 12px;
  }
}
</style>